import Vue from "vue";
import Vuex from "vuex";
import {
  reqCategory1List,
  reqCategory2List,
  reqCategory3List,
} from "@/api/product/category";

//组件可以通过this.$store访问
Vue.use(Vuex);

export default {
  namespaced: true, //声明后续state，mutation，actions调用都要加上命名空间

  state: {
    //这是数据id项，用于数据交互
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,

    //这是具体数据列表
    category1List: [],
    category2List: [],
    category3List: [],
  },

  //action 修改异步状态
  actions: {
    // 1. 获取一级分类数据
    async getCategory1List({ commit }) {
      const result = await Vue.prototype.$API.category.reqCategory1List();
      commit("GET_CATEGORY1_LIST", result);
    },
    // 2. 获取二级分类数据
    async getCategory2List({ commit }, category1Id) {
      // console.log(Vue.prototype.$API);
      //console.log("category1Id", category1Id);
      const result = await Vue.prototype.$API.category.reqCategory2List(
        category1Id
      );
      commit("GET_CATEGORY2_LIST", { result, category1Id });
      console.log('cccc',result)
    },
    // 3. 获取三级分类数据
    async getCategory3List({ commit }, category2Id) {
      const result = await Vue.prototype.$API.category.reqCategory3List(
        category2Id
      );
      commit("GET_CATEGORY3_LIST", { result, category2Id });
    },
    // 4. 给category3Id赋值
    setCategory3Id({ commit }, category3Id) {
      commit("SET_CATEGORY3_ID", category3Id);
    },
  },
  // mutations变更状态
  mutations: {
    // 1. 渲染一级列表数据
    GET_CATEGORY1_LIST(state, category1List) {
      state.category1List = category1List.data;
    },
    // 2. 渲染二级列表数据
    GET_CATEGORY2_LIST(state, { result, category1Id }) {
      state.category1Id = category1Id;
      state.category2Id = undefined;
      state.category3Id = undefined;
      state.category2List = result.data;
      //清空category3List的数据
      state.category3List = [];
    },
    // 3. 渲染三级列表数据
    GET_CATEGORY3_LIST(state, { result, category2Id }) {
      state.category2Id = category2Id;
      state.category3Id = undefined;
      state.category3List = result.data;
    },
    // 4. category3Id赋值
    SET_CATEGORY3_ID(state, category3Id) {
      state.category3Id = category3Id;
    },
  },
  // 使用getters对数据进行筛选
  getters: {},
};
